package utils

import (
	"fmt"
	"strconv"

	"github.com/gin-gonic/gin"
)

// GetUintParam 从 URL 参数中获取 uint 类型的值
func GetUintParam(c *gin.Context, param string) (uint, error) {
	value := c.Param(param)
	if value == "" {
		return 0, fmt.Errorf("parameter %s is required", param)
	}

	intValue, err := strconv.ParseUint(value, 10, 32)
	if err != nil {
		return 0, fmt.Errorf("parameter %s must be a positive integer", param)
	}

	return uint(intValue), nil
}

// GetPaginationParams 从查询参数中获取分页参数
func GetPaginationParams(c *gin.Context) (page, pageSize int) {
	page, _ = strconv.Atoi(c.DefaultQuery("page", "1"))
	pageSize, _ = strconv.Atoi(c.DefaultQuery("page_size", "10"))

	// 确保最小值和最大值
	if page < 1 {
		page = 1
	}
	if pageSize < 1 {
		pageSize = 10
	}
	if pageSize > 100 {
		pageSize = 100
	}

	return page, pageSize
}

// GetQueryParam 从查询参数中获取字符串值
func GetQueryParam(c *gin.Context, param, defaultValue string) string {
	value := c.Query(param)
	if value == "" {
		return defaultValue
	}
	return value
}

// GetBoolQueryParam 从查询参数中获取布尔值
func GetBoolQueryParam(c *gin.Context, param string, defaultValue bool) bool {
	value := c.Query(param)
	if value == "" {
		return defaultValue
	}
	return value == "true" || value == "1" || value == "t"
}
